/**
 * Copyright (c) 2015 - present LibDriver All rights reserved
 * 
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. 
 *
 * @file      spi.c
 * @brief     spi源文件
 * @version   1.0.0
 * @author    Shifeng Li
 * @date      2022-11-11
 *
 * <h3>历史</h3>
 * <table>
 * <tr><th>日期        <th>版本  <th>作者      <th>描述
 * <tr><td>2022/11/11  <td>1.0      <td>Shifeng Li  <td>首次上传
 * </table>
 */

#include "spi.h"

/**
 * @brief spi变量定义
 */
SPI_HandleTypeDef g_spi_handle;        /**< spi句柄 */

/**
 * @brief  SPI片选引脚初始化
 * @return 状态码
 *         - 0 成功
 * @note   CS引脚为PA4
 */
static uint8_t a_spi_cs_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    
    /* 使能CS GPIO时钟 */
    __HAL_RCC_GPIOA_CLK_ENABLE();
    
    /* GPIO初始化 */
    GPIO_InitStruct.Pin = GPIO_PIN_4;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    
    return 0;
}

/**
 * @brief     spi总线初始化
 * @param[in] mode spi模式
 * @return    状态码
 *            - 0 成功
 *            - 1 初始化失败
 * @note      SCLK为PA5, MOSI为PA7, MISO为PA6, CS为PA4
 */
uint8_t spi_init(spi_mode_t mode)
{
    /* 使能SPI1时钟 */
    __HAL_RCC_SPI1_CLK_ENABLE();
    
    /* 使能GPIO时钟 */
    __HAL_RCC_GPIOA_CLK_ENABLE();
    
    /* SPI1 GPIO配置 */
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;  /* F103需要上拉 */
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* 配置SPI1引脚复用 */
    __HAL_AFIO_REMAP_SPI1_ENABLE();  /* F103需要重映射SPI1引脚 */

    g_spi_handle.Instance = SPI1;
    g_spi_handle.Init.Mode = SPI_MODE_MASTER;
    g_spi_handle.Init.Direction = SPI_DIRECTION_2LINES;
    g_spi_handle.Init.DataSize = SPI_DATASIZE_8BIT;
    
    /* 设置模式 */
    if (mode == SPI_MODE_0)
    {
        g_spi_handle.Init.CLKPolarity = SPI_POLARITY_LOW;
        g_spi_handle.Init.CLKPhase = SPI_PHASE_1EDGE;
    }
    else if (mode == SPI_MODE_1)
    {
        g_spi_handle.Init.CLKPolarity = SPI_POLARITY_LOW;
        g_spi_handle.Init.CLKPhase = SPI_PHASE_2EDGE;
    }
    else if (mode == SPI_MODE_2)
    {
        g_spi_handle.Init.CLKPolarity = SPI_POLARITY_HIGH;
        g_spi_handle.Init.CLKPhase = SPI_PHASE_1EDGE;
    }
    else
    {
        g_spi_handle.Init.CLKPolarity = SPI_POLARITY_HIGH;
        g_spi_handle.Init.CLKPhase = SPI_PHASE_2EDGE;
    }
    
    /* F103的SPI配置 */
    g_spi_handle.Init.NSS = SPI_NSS_SOFT;
    g_spi_handle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
    g_spi_handle.Init.FirstBit = SPI_FIRSTBIT_MSB;
    g_spi_handle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    g_spi_handle.Init.TIMode = SPI_TIMODE_DISABLE;  /* F103需要禁用TI模式 */
    
    /* SPI初始化 */
    if (HAL_SPI_Init(&g_spi_handle) != HAL_OK)
    {
        return 1;
    }
    
    return a_spi_cs_init();
}

/**
 * @brief  spi总线反初始化
 * @return 状态码
 *         - 0 成功
 *         - 1 反初始化失败
 * @note   无
 */
uint8_t spi_deinit(void)
{
    /* CS反初始化 */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_4);
    
    /* SPI反初始化 */
    if (HAL_SPI_DeInit(&g_spi_handle) != HAL_OK)
    {
        return 1;
    }
    
    return 0;
}

/**
 * @brief     spi总线写命令
 * @param[in] *buf 数据缓冲区指针
 * @param[in] len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写失败
 * @note      无
 */
uint8_t spi_write_cmd(uint8_t *buf, uint16_t len)
{
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 发送缓冲区数据 */
        res = HAL_SPI_Transmit(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
            
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线写
 * @param[in] addr spi寄存器地址
 * @param[in] *buf 数据缓冲区指针
 * @param[in] len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写失败
 * @note      无
 */
uint8_t spi_write(uint8_t addr, uint8_t *buf, uint16_t len)
{
    uint8_t buffer;
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 发送地址 */
    buffer = addr;
    res = HAL_SPI_Transmit(&g_spi_handle, (uint8_t *)&buffer, 1, 1000);
    if (res != HAL_OK)
    {
        /* 设置CS为高电平 */
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
        
        return 1;
    }
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 发送缓冲区数据 */
        res = HAL_SPI_Transmit(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
            
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线写16位地址
 * @param[in] addr spi寄存器地址
 * @param[in] *buf 数据缓冲区指针
 * @param[in] len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写失败
 * @note      无
 */
uint8_t spi_write_address16(uint16_t addr, uint8_t *buf, uint16_t len)
{
    uint8_t buffer[2];
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 发送地址 */
    buffer[0] = (addr >> 8) & 0xFF;
    buffer[1] = addr & 0xFF;
    res = HAL_SPI_Transmit(&g_spi_handle, (uint8_t *)buffer, 2, 1000);
    if (res != HAL_OK)
    {
        /* 设置CS为高电平 */
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
       
        return 1;
    }
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 发送缓冲区数据 */
        res = HAL_SPI_Transmit(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
           
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线读命令
 * @param[out] *buf 数据缓冲区指针
 * @param[in]  len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 读失败
 * @note      无
 */
uint8_t spi_read_cmd(uint8_t *buf, uint16_t len)
{
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 接收数据到缓冲区 */
        res = HAL_SPI_Receive(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
            
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线读
 * @param[in]  addr spi寄存器地址
 * @param[out] *buf 数据缓冲区指针
 * @param[in]  len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 读失败
 * @note      无
 */
uint8_t spi_read(uint8_t addr, uint8_t *buf, uint16_t len)
{
    uint8_t buffer;
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 发送地址 */
    buffer = addr;
    res = HAL_SPI_Transmit(&g_spi_handle, (uint8_t *)&buffer, 1, 1000);
    if (res != HAL_OK)
    {
        /* 设置CS为高电平 */
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
       
        return 1;
    }
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 接收数据到缓冲区 */
        res = HAL_SPI_Receive(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
           
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线读16位地址
 * @param[in]  addr spi寄存器地址
 * @param[out] *buf 数据缓冲区指针
 * @param[in]  len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 读失败
 * @note      无
 */
uint8_t spi_read_address16(uint16_t addr, uint8_t *buf, uint16_t len)
{
    uint8_t buffer[2];
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 发送地址 */
    buffer[0] = (addr >> 8) & 0xFF;
    buffer[1] = addr & 0xFF;
    res = HAL_SPI_Transmit(&g_spi_handle, (uint8_t *)buffer, 2, 1000);
    if (res != HAL_OK)
    {
        /* 设置CS为高电平 */
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
       
        return 1;
    }
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 接收数据到缓冲区 */
        res = HAL_SPI_Receive(&g_spi_handle, buf, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
           
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi发送接收
 * @param[in]  *tx 发送缓冲区指针
 * @param[out] *rx 接收缓冲区指针
 * @param[in]  len 数据缓冲区长度
 * @return    状态码
 *            - 0 成功
 *            - 1 发送接收失败
 * @note      无
 */
uint8_t spi_transmit(uint8_t *tx, uint8_t *rx, uint16_t len)
{
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 如果长度大于0 */
    if (len > 0)
    {
        /* 发送接收数据 */
        res = HAL_SPI_TransmitReceive(&g_spi_handle, tx, rx, len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
            
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}

/**
 * @brief     spi总线写读
 * @param[in]  *in_buf 输入缓冲区指针
 * @param[in]  in_len 输入长度
 * @param[out] *out_buf 输出缓冲区指针
 * @param[in]  out_len 输出长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写读失败
 * @note      无
 */
uint8_t spi_write_read(uint8_t *in_buf, uint32_t in_len, uint8_t *out_buf, uint32_t out_len)
{
    uint8_t res;
    
    /* 设置CS为低电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
    
    /* 如果输入长度大于0 */
    if (in_len > 0)
    {
        /* 发送输入缓冲区数据 */
        res = HAL_SPI_Transmit(&g_spi_handle, in_buf, in_len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
           
            return 1;
        }
    }
    
    /* 如果输出长度大于0 */
    if (out_len > 0)
    {
        /* 接收输出缓冲区数据 */
        res = HAL_SPI_Receive(&g_spi_handle, out_buf, out_len, 1000);
        if (res != HAL_OK)
        {
            /* 设置CS为高电平 */
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
           
            return 1;
        }
    }
    
    /* 设置CS为高电平 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
    
    return 0;
}
